<template>
	<view class="content">

		<z-paging ref="paging" :refresher-only="true" :fixed="false" @query="GetPageInfo">
			<template #top>

				<u-navbar class="head-index" :fixed="false" :safeAreaInsetTop="true" titleStyle="color:#fff"
					:autoBack="true" leftIconColor="#fff" title="统计" rightIcon="reload"
					@rightClick="RefreshBtn"></u-navbar>

				<!-- 时间选择器 -->
				<view class="example-body">
					<uni-datetime-picker v-model="singleTimes" @change="ChangeDate" type="daterange" :end="EndDate"
						rangeSeparator="至"></uni-datetime-picker>
				</view>

				<!-- <u-sticky bgColor="#fff"> -->
				<view
					style="display: flex;justify-content: space-between;align-items: center;background-color: #51d0d0;">
					<u-tabs style="flex: 1;" :list="TabList" :current="TabsIndex" @change="ChangeTab" lineColor="#fff"
						:activeStyle="{'font-size':'24px','font-weight': '600'}"></u-tabs>

					<view style="width: fit-content;background-color: transparent !important;padding: 0 6px;">
						<u-subsection style="min-width: 100px;" :list="ChangeTypeList" :current="curNow"
							@change="sectionChange"></u-subsection>
					</view>
				</view>
				<!-- </u-sticky> -->
			</template>


			<!-- 主内容 -->
			<view class="MainBox">
				<view class="charts-box">
					<qiun-data-charts type="line" :opts="opts" :chartData="chartData"
						:ontouch="true"></qiun-data-charts>
				</view>

				<!-- 环形图 -->
				<view class="AnnularProgressBox">
					<!-- percent环形百分比 size尺寸大小； strokeWidth环形粗细 -->
					<view class="progressBox" v-if="ShowFun(item,index)" v-for="(item,index) in AnnularProgress"
						:key="index">
						<m-progress-circle :progress="Number(item.HGPercentage)" :canvasId="String(index)" :radius="60"
							:lineWidth="6" :innerTextSize="16" :progressColor="item.HGColor" :BottomTextSize="12">
						</m-progress-circle>
						<view class="text" :style="{'color':item.HGColor }">
							<text>{{item.HGText}}</text>
						</view>
					</view>
				</view>


				<view style="margin-top: 40px;">
					<uni-row class="CommonBox" v-if="ShowAnnular">
						<uni-col v-for="(item,index) in BottomList" :key="index" :span="12" class="CommonCardParent">
							<view class="CommonCard">
								<view class="Card">
									<u-icon :name="item.Icon" :color="item.IconColor" size="40"></u-icon>

									<view class="RightContent">
										<view>
											<text class="Nums">{{item.Nums}}</text>
											<text class="Unit">{{item.Unit}}</text>
										</view>
										<!-- 合格数、不合格数 -->
										<view>
											<text class="Text">{{item.Text}}</text>
										</view>
									</view>

								</view>
							</view>
						</uni-col>
					</uni-row>
				</view>

			</view>

		</z-paging>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				StartDate: null, // 限制开始时间
				EndDate: null, // 结束时间
				singleTimes: [], // 日期选择控件
				TabList: [ // Tabs标签数组
					{
						name: '来料检',
						value: 'LLJYD',
						id: 0
					}, {
						name: '首件检',
						value: 'SJJ',
						id: 1
					}, {
						name: '巡检',
						value: 'XJ',
						id: 2
					}, {
						name: '末件检',
						value: 'MJJ',
						id: 3
					}, {
						name: '成品检',
						value: 'CPJ',
						id: 4
					},
				],
				TabsIndex: 0, // 手动记录Tab的 active
				ChangeTypeList: [{ // 分段器内容
						name: '数量'
					},
					{
						name: '批次'
					},
				],
				curNow: 0, // 分段器索引
				curNowCopy: 0, // 分段器索引备份， 判断选中项是否是上次所选的，避免重复请求
				TypeTimer: null, // 简易的防抖，防止切换频繁
				chartData: {},
				opts: {
					color: ["#91CB74", "#EE6666", "#1890FF", "#FAC858", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 10, 0, 15],
					enableScroll: true,
					legend: {},
					xAxis: {
						disableGrid: true,
						// calibration: true,
						scrollShow: true,
						itemCount: 4,
						// min: 0,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						data: [{
							calibration: true,
							min: 0,
							// max: 100
						}]
					},
					extra: {
						line: {
							type: "curve",
							width: 2,
							activeType: "hollow"
						}
					}
				},

				ShowAnnular: false,
				AnnularProgress: [], // 环形进度数据
				ResetData: [ // 环形进度数据重置
					{
						"HGPercentage": 0,
						"HGColor": "#4ADA88",
						"HGText": "合格率",
						"HGID": 0
					}, {
						"HGPercentage": 0,
						"HGColor": "#da4518",
						"HGText": "不合格率",
						"HGID": 1
					}, {
						"HGPercentage": 0,
						"HGColor": "#24b0da",
						"HGText": "让步放行",
						"HGID": 2
					},
				],

				BottomList: [ // 底部数据组
					{
						Icon: 'share',
						IconColor: '#ffb011',
						Nums: 0,
						Text: '检验次数',
						Unit: '次',
					}, {
						Icon: 'share',
						IconColor: '#ff785d',
						Nums: 0,
						Text: '不合格次数',
						Unit: '次',
					}, {
						Icon: 'share',
						IconColor: '#97ffa8',
						Nums: 0,
						Text: '合格次数',
						Unit: '次',
					},
				],
				request1: null,
				request2: null,
				request3: null,
			};

		},
		onLoad() {},
		onReady() {
			var that = this;
			this.$utils.showLoading();
			// 设置限制时间范围
			// that.StartDate = dateFormat((new Date()).getTime() - 1000 * 60 * 60 * 24 * 10, 'yyyy-MM-dd')
			that.EndDate = dateFormat((new Date()).getTime(), 'yyyy-MM-dd')

			// 设置初始化时间
			that.singleTimes = [dateFormat((new Date()).getTime() - 1000 * 60 * 60 * 24 * 30 * 2, 'yyyy-MM-dd'),
				dateFormat((
					new Date()).getTime(), 'yyyy-MM-dd')
			];

			setTimeout(() => {
				// 获取页面数据
				that.GetPageInfo();
			}, 500);

		},
		watch: {
			curNow: {
				handler(newVal, oldVal) {
					var that = this;

					clearTimeout(that.TypeTimer);

					that.TypeTimer = setTimeout(() => {
						if (that.curNowCopy != newVal) { // 判断选中项是否是上次所选的，避免重复请求

							// 获取页面数据
							this.GetPageInfo();

							that.curNowCopy = newVal; // 记录当前选中
						}
					}, 600);
				},
				// immediate: true
			}
		},
		methods: {
			ShowFun(data, index) {
				if (this.curNow == 0 && index == 2) {
					return false;
				} else {
					return true;
				}
			},
			sectionChange(index) { // 切换显示状态
				var that = this;
				if (this.curNow == index) return;
				this.$utils.showLoading();
				this.curNow = index;
			},
			ChangeDate() { // 修改日期
				var that = this;

				that.RefreshBtn();
			},
			RefreshBtn() { // 刷新
				var that = this;

				that.ChangeTab(that.TabList[that.TabsIndex])
			},
			ChangeTab(data) { // 切换Tab栏
				var that = this;
				this.$utils.showLoading();

				// 因为切换Tab无法改变索引，手动记录一下
				that.TabsIndex = data.id

				setTimeout(() => {
					that.GetPageInfo()
				}, 500)
			},
			GetPageInfo() {
				let that = this;

				let data = this.TabList[this.TabsIndex];
				try {
					/* 获取charts数据 */
					let obj = {
						FType: data.value, // 检验项
						FBdate: that.singleTimes[0], // 开始时间
						FEdate: that.singleTimes[1], // 结束时间
						LX: that.curNow + 1, // 数量 1 ；批次 2
					};
					that.request1 = that.Request.PromiseRequest('JYTJJK', obj);

					that.request1.promise.then((data) => {
						let res = {
							categories: [], // x轴数据
							series: []
						}

						let obj = {
							name: '合格数',
							data: []
						}
						let BHGObj = {
							name: '不合格数',
							data: []
						}
						if (data.status == 200) {

							data.data.ds.forEach(item => {
								res.categories.push(add0(item.DAY))

								obj.data.push(item.HGNumber)
								BHGObj.data.push(item.BHGNumber)
							})

							res.series.push(obj)
							res.series.push(BHGObj)
							that.chartData = JSON.parse(JSON.stringify(res));
						}


					}).then((result) => {
						this.request1 = null;

						/* 获取环形图数据 */
						that.request2 = that.Request.PromiseRequest('JYTJJK2', obj);
						return that.request2.promise;
					}).then((result) => {
						this.request2 = null;

						if (result.status == 200) {

							let NewData = JSON.parse(JSON.stringify(that.ResetData))
							if (result.data.ds.length) {
								NewData[0]['HGPercentage'] = result.data.ds[0]['HGPercentage']
								NewData[1]['HGPercentage'] = result.data.ds[0]['BHGPercentage']
								NewData[2]['HGPercentage'] = result.data.ds[0]['RBFXHGPercentage']
								that.AnnularProgress = NewData.sort(customSort)
							} else {
								that.AnnularProgress = that.ResetData.sort(customSort)
							}
						}


						/* 获取环形图数据 */
						that.request3 = that.Request.PromiseRequest('JYTJJK3', obj);
						return that.request3.promise;
					}).then((data) => {
						// 请求2成功的处理逻辑
						if (data.status == 200) {

							let Arr = [ // 底部数据组
								{
									Icon: 'share',
									IconColor: '#ffb011',
									Nums: 0,
									Text: '检验数量',
									Unit: '个',
								}, {
									Icon: 'share',
									IconColor: '#ff785d',
									Nums: 0,
									Text: '不合格数量',
									Unit: '个',
								}, {
									Icon: 'share',
									IconColor: '#97ffa8',
									Nums: 0,
									Text: '合格数量',
									Unit: '个',
								},
							];


							Arr[0].Nums = data.data.ds[0].JYSL;
							Arr[1].Nums = data.data.ds[0].BHGSL;
							Arr[2].Nums = data.data.ds[0].HGSL;

							if (data.data.ds[0].RBCS >= 0) {
								Arr[3] = {
									Icon: 'share',
									IconColor: '#4e77ff',
									Nums: data.data.ds[0].RBCS,
									Text: '让步批次',
									Unit: '次',
								}
							}

							if (that.curNow == 1) {
								Arr[0].Text = '检验批次';
								Arr[1].Text = '不合格批次';
								Arr[2].Text = '合格批次';

								Arr.map(item => {
									item.Unit = '次'
								})
							}

							that.BottomList = Arr;

							// that.BottomList[3].Nums = data.data.ds[0].RBCS || null;

							that.ShowAnnular = true;
						}

						this.$utils.hideLoading();

						that.$refs.paging.endRefresh();
					}).catch((error) => {
						this.$utils.hideLoading();
						that.$refs.paging.endRefresh();

						uni.showToast({
							title: '请求失败，请重试',
							icon: 'none'
						})
					});

				} catch (e) {
					// TODO handle the exception
					console.log(JSON.stringify(e))
					this.$utils.hideLoading();
					that.$refs.paging.endRefresh();
				}
			},

		}
	}

	/** 根据数组对象中的属性名，重排数组
	 * @param TypeName  	数组对象中对比的属性名
	 * @param ChangeList  	对比的数组
	 */
	const ChangeList = ['合格率', '不合格率', '让步放行'];
	const customSort = (a, b) => {
		// 获取字符串在数组中的索引
		let indexA = ChangeList.indexOf(a['HGText']);
		let indexB = ChangeList.indexOf(b['HGText']);

		// 比较索引值并返回排序结果
		return indexA - indexB
	}

	//修改月、天的格式，保持两位数显示
	const add0 = (m) => {
		return m < 10 ? '0' + m : m
	}

	// 转时间格式
	const dateFormat = (date, fmt) => {
		date = new Date(date)
		var a = ['日', '一', '二', '三', '四', '五', '六']
		var o = {
			'M+': date.getMonth() + 1, // 月份
			'd+': date.getDate(), // 日
			'h+': date.getHours(), // 小时
			'm+': date.getMinutes(), // 分
			's+': date.getSeconds(), // 秒
			'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
			'S': date.getMilliseconds(), // 毫秒
			'w': date.getDay(), // 周
			'W': a[date.getDay()], // 大写周
			'T': 'T'
		}
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		for (var k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k])
					.length)))
			}
		}
		return fmt
	}
</script>

<style lang="scss">
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	.content {
		/* 给顶部盒子安全高度 */
		// padding-top: var(--status-bar-height);
		display: flex;
		flex-direction: column;
		height: 94vh;

		.head-index {

			.u-navbar__content__right {
				.u-icon__icon {
					color: #fff !important;
				}
			}

			// 顶部导航栏 navbar点击左侧会有改变透明的的操作，直接强制赋值为1
			.u-navbar__content__left {
				opacity: 1 !important;
			}
		}

		// 时间
		.example-body {
			padding: 6px 20px;
			color: #fff;
			background-color: #51d0d0;

			.uni-date-editor--x {
				background-color: #fff;
			}
		}

		// Tab页签
		.u-tabs__wrapper__nav {
			color: #fff !important;
			background-color: #51d0d0 !important;

			.u-tabs__wrapper__nav__item__text {
				color: #fff !important;
			}
		}

		.u-tabs__wrapper__nav__item {
			width: fit-content !important;
		}

		.MainBox {
			flex: 1;
			padding: 10px 15px;
			overflow: auto;
			padding-bottom: 50px;
		}
	}

	.u-nav-slot {
		/* min-width: 80px; */
		width: fit-content;
	}

	.uni-select {
		min-width: 150px;
		border: none !important;
	}

	.charts-box {
		width: 100%;
		height: 300px;
	}

	.AnnularProgressBox {
		display: flex;
		justify-content: space-around;
		align-items: center;

		.progressBox {
			position: relative;
			width: 180rpx;
			height: 180rpx;
			margin: 0 auto;
			margin-top: 33rpx;

			.centerTxt {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);

				.num {
					font-size: 22rpx;
					font-family: Arial;
					font-weight: bold;
					// color: #38393A;
				}
			}

			.text {
				font-size: 16px;
				font-family: PingFang SC;
				font-weight: 400;
				// color: #8A8B8B;
				margin-top: 10rpx;
				text-align: center !important;
			}
		}
	}

	.u-grid-item {
		flex-direction: row !important;
		align-items: center;
		padding: 20rpx 0;

		.grid-text {
			font-size: 14px;
			color: #909399;
			padding: 10rpx 0 20rpx 0rpx;
			/* #ifndef APP-PLUS */
			box-sizing: border-box;
			/* #endif */
		}
	}

	// 圆环
	.u-progress-content {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.u-progress-dot {
		width: 16rpx;
		height: 16rpx;
		border-radius: 50%;
		background-color: #fb9126;
	}

	.u-progress-info {
		font-size: 28rpx;
		padding-left: 16rpx;
		letter-spacing: 2rpx
	}

	// 底部宫格样式
	.CommonBox {

		.CommonCardParent {

			// &:first-child {
			// 	border-right: 1px solid;
			// 	border-image: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(0, 187, 242, 0.4) 60%, rgba(0, 187, 242, 0.6) 99%) 2 2 2 2;
			// }

			// &:nth-child(2) {
			// 	border-bottom: 1px solid;
			// 	border-image: linear-gradient(90deg, rgba(0, 187, 242, 0.6) 99%, rgba(0, 187, 242, 0.4) 60%, rgba(255, 255, 255, 0) 0%) 2 2 2 2;
			// 	// border-image: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(0, 187, 242, 0.4) 60%, rgba(0, 187, 242, 0.6) 99%) 2 2 2 2;
			// }

			// &:nth-child(3) {
			// 	border-top: 1px solid;
			// 	border-image: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(0, 187, 242, 0.4) 60%, rgba(0, 187, 242, 0.6) 99%) 2 2 2 2;
			// }

			// &:nth-child(4) {
			// 	border-left: 1px solid;
			// 	border-image: linear-gradient(180deg, rgba(0, 187, 242, 0.6) 99%, rgba(0, 187, 242, 0.4) 60%, rgba(255, 255, 255, 0) 0%) 2 2 2 2;
			// 	// border-image: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(0, 187, 242, 0.4) 60%, rgba(0, 187, 242, 0.6) 99%) 2 2 2 2;
			// }

			.CommonCard {
				width: 100%;
				text-align: center;
				padding: 20px 0;

				.Card {
					display: flex;
					align-items: center;
					justify-content: center;

					.RightContent {
						margin-left: 12px;
						color: #707070;

						.Nums {
							font-size: 20px;
						}

						.Unit {
							font-size: 12px;
							margin-left: 4px;
						}

						.Text {
							font-size: 14px;
						}
					}
				}
			}

		}
	}
</style>